package gr.handmademarket.ui;

import gr.handmademarket.bl.operations.LoginOperation;
import gr.handmademarket.po.implementations.PurchaseItem;
import gr.handmademarket.po.interfaces.User;

import java.util.ArrayList;
import java.util.List;

import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.authroles.authorization.strategies.role.Roles;
import org.apache.wicket.request.Request;

/**
 * Authenticated web session.
 */
public class WebHandMadeSession 
extends AuthenticatedWebSession{

	/**
	 * serialVersionUID
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * the session has a user.
	 */
	private User user;
	
	/**
	 * the list of products user has selected.
	 */
	private List<PurchaseItem> userItems = new ArrayList<PurchaseItem>();

	/**
	 * Creates a new WebHandMadeSession object. 
	 *
	 * @param request
	 */
	public WebHandMadeSession(Request request) {
		super(request);
	}

	@Override
	public boolean authenticate(String username, String password) {
		if (user == null){
			LoginOperation op = new LoginOperation();
			op.setUsername(username);
			op.setPassword(password);
			op.execute();
			user = op.getUser();
		}
		return user != null;
	}

	@Override
	public Roles getRoles() {
		if (user == null){
			return null;
		} else{
			return new Roles(user.getRole().name());
		}
	}

	/**
	 * @return user.
	 */
	public User getUser() {
		return user;
	}

	/**
	 * @param user
	 */
	public void setUser(User user) {
		this.user = user;
	}
	
	/**
	 * 
	 * @return user items.
	 */
	public List<PurchaseItem> getUserItems() {
		return userItems;
	}

	/**
	 * 
	 * @param userItems
	 */
	public void setUserItems(List<PurchaseItem> userItems) {
		this.userItems = userItems;
	}
	
	public double getTotalAmount(){
		Double amount = 0d;
		for (PurchaseItem item : userItems){
			amount += item.getQuantity() * item.getProduct().getPrice();
		}
		return amount;
	}
	
}
